package net.tp.struct;

import java.util.*;

/**
 * Read an iterable in a forwarding direction.
 * <p>
 * This is to clarify that some algorithms only need to read a sequence without mutating it.
 *
 * @author Trung Phan
 */
public class SeqReader<E> {

    final private Iterator<E> iterator;

    private E next;

    private boolean hasNext;

    public SeqReader(Iterator<E> iterator) {
        this.iterator = iterator;
    }

    public SeqReader(Iterable<E> iterable) {
        this.iterator = iterable.iterator();
    }

    public E next() {
        if (hasNext) {
            E result = next;
            hasNext = false;
            next = null;
            return result;
        }
        else return iterator.next();
    }

    public E peek() {
        if (!hasNext) {
            next = iterator.next();
            hasNext = true;
        }
        return next;
    }

    public boolean hasNext() {
        return hasNext || iterator.hasNext();
    }
}
